package cn.edu.zstu.qingzhu.qingzhushop.controller.admin;

import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import cn.edu.zstu.qingzhu.qingzhushop.entity.Role;
import cn.edu.zstu.qingzhu.qingzhushop.entity.User;
import cn.edu.zstu.qingzhu.qingzhushop.service.IRoleService;
import cn.edu.zstu.qingzhu.qingzhushop.service.IUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ShenTuZhiGang
 * @version 1.0.0
 * @date 2020-07-29 11:20
 */
@RestController
@RequestMapping("/system/admin")
@Api(tags = "系统管理管理员设置接口")
public class AdminController {
    @Autowired
    IUserService iUserService;
    @Autowired
    IRoleService iRoleService;

    @GetMapping("/")
    public List<User> getAllUsers(@RequestParam("keyword") String keyword) {
        return iUserService.getAllUserWithRoles(iUserService.getCurrentAuthenticationUser().getId()
                , keyword);
    }

    @PutMapping("/")
    public ResponseBean updateUser(@RequestBody User user) {
        if (iUserService.updateById(user) == true) {
            return ResponseBean.ok("更新成功!");
        }
        return ResponseBean.error("更新失败!");
    }

    @GetMapping("/roles")
    public List<Role> getAllRoles() {
        return iRoleService.list();
    }

    @PutMapping("/role/edit/{userId}")
    public ResponseBean updateUserRole(@PathVariable("userId") Integer userId,
                                       @RequestParam("roleIds") Integer[] roleIds) {
        if (iUserService.updateUserRole(userId, roleIds)) {
            return ResponseBean.ok("更新成功!");
        }
        return ResponseBean.error("更新失败!");
    }

    @DeleteMapping("/{id}")
    public ResponseBean deleteUserById(@PathVariable Integer id) {
        if (iUserService.removeById(id) == true) {
            return ResponseBean.ok("删除成功!");
        }
        return ResponseBean.error("删除失败!");
    }
}
